﻿using System.Collections.Generic;
using System.Linq;
using doufu.Common;
using doufu.Common.Extensen;

namespace doufu.Service
{
    /// <summary>
    /// Tools
    /// </summary>
    public class ToolsService
    {
        /// <summary>
        /// 执行sql
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public List<dynamic> Excute(string sql)
        {
            return Excute<dynamic>(sql);
        }

        private List<T> Excute<T>(string sql)
        {
            return CommonDac.Query(db =>
            {
                db.EnableAutoSelect = false;
                var ret = db.Fetch<T>(sql);
                return ret;
            });
        }

        public Model.TableInfo GetTableInfo(string table)
        {
            var tableInfo = new Model.TableInfo
                                {
                                    name = table,
                                    Columnses = Excute<Model.Columns>("pragma table_info (" + table + ")")
                                };
            tableInfo.sql_info = Excute<string>(string.Format("select sql from sqlite_master where type='table' and name='{0}'", table)).FirstOrDefault() ?? string.Empty;
            var column = tableInfo.sql_info.Split('[').Select(x => string.Format("[{0}", x)).ToArray();

            tableInfo.Columnses.ForEach(c =>
                                            {
                                                c.auto_increment = column.Any(x => x.Contains(string.Format("[{0}]", c.name)) && x.Contains("AUTOINCREMENT"));
                                                if (c.type.Contains("("))
                                                {
                                                    var type = c.type;
                                                    c.type = c.type.Substring(0, type.IndexOf('('));
                                                    c.length = type.Replace(c.type, "").Replace(")", "").Replace("(", "");
                                                }
                                                //if (c.type == "INT")
                                                //{
                                                //    c.type = "INTEGER";
                                                //}
                                            });
            tableInfo.columns_array = tableInfo.Columnses.ToJson();

            return tableInfo;
        }
    }
}